﻿using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace 查看EFCore生成的SQL语句
{
    public class MyContext:DbContext
    {
        private readonly ILoggerFactory _loggerFactory;
        public MyContext(ILoggerFactory loggerFactory)
        {
            _loggerFactory = loggerFactory;
        }

        public DbSet<Book> Books { get; set; }        
        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            base.OnConfiguring(optionsBuilder);
            optionsBuilder.UseSqlServer("Server=.;Database=NetTest; Trusted_Connection=True;TrustServerCertificate=True;MultipleActiveResultSets=true");
            
            //标准日志
            optionsBuilder.UseLoggerFactory(_loggerFactory);

            //简单日志：写法1
            optionsBuilder.LogTo(Console.WriteLine);

            //简单日志：写法2
            optionsBuilder.LogTo(msg =>
            {
                if (!msg.Contains("CommandExecuting")) return;
                Console.WriteLine(msg);
            });
        }

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);
            modelBuilder.ApplyConfigurationsFromAssembly(this.GetType().Assembly);
        }
    }
}
